package com.yanze.schoolinformation.view.my.person;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;

import com.yanze.schoolinformation.R;
import com.yanze.schoolinformation.databinding.ActivityCropBinding;
import com.yanze.schoolinformation.utils.ClickUtils;
import com.yanze.schoolinformation.utils.FilePathManager;
import com.yanze.schoolinformation.utils.ToolUtils;
import com.yanze.schoolinformation.viewModule.person.PersonViewModel;

public class CropActivity extends AppCompatActivity implements View.OnClickListener {

    public static String CRAP_FILE_KEY = "crap.file.key";
    private String filePath;//需要剪裁的图片路径
    private ActivityCropBinding databinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        databinding = DataBindingUtil.setContentView(this, R.layout.activity_crop);

        Intent intent = getIntent();
        filePath = intent.getStringExtra(CRAP_FILE_KEY);

        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);//根据屏幕宽度进行采样率压缩
        int wid = wm.getDefaultDisplay().getWidth();
        int hei = wm.getDefaultDisplay().getHeight();
        Bitmap bitmap = ToolUtils.decodeBigmapFromFile(filePath, wid, hei);

        databinding.cropCropImage.setFixedAspectRatio(true);
        databinding.cropCropImage.setImageBitmap(bitmap);
        databinding.btnSure.setOnClickListener(this);
        databinding.btnCancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (!ClickUtils.isFastClick()) {//防止点击过快//防抖1s
            return;
        }
        switch (v.getId()) {
            case R.id.btn_sure:
                //确定剪裁
                Bitmap bit = databinding.cropCropImage.getCroppedImage();
                //压缩图片
                ToolUtils.compressBitmap(bit, FilePathManager.getCropdFilePath(this,filePath.substring(filePath.lastIndexOf("."))), 100);
                setResult(PersonViewModel.RESULT_CROP);
                finish();
                break;
            case R.id.btn_cancel:
                finish();
                break;
        }
    }

    /**
     * 入口
     */
    public static void start(Activity activity, String filePath) {
        Intent intent = new Intent(activity, CropActivity.class);
        intent.putExtra(CRAP_FILE_KEY, filePath);
        activity.startActivityForResult(intent, PersonViewModel.REQUEST_CROP);
    }
}
